<?php
namespace Home\Controller;

class ProductController extends \Home\Controller\BaseController
{
	/**
	 * 基金产品列表
	 * @author 尹雷
	 */
	public function productList()
	{
		$param = I('params');
		if(!$param) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		$size = I('data.size', 5, '/^[1-9]\d*$/', $param) ;
		$page = I('data.page', 1, '/^[1-9]\d*$/', $param) ;
		
		//构造查询条件
		$where = array();
		if($param['cat_id']) $where['fc.cat_id'] = I('data.cat_id', '', '/^[1-9]\d*$/', $param);
		
		//查询产品列表
		$this->productList1($where, $page, $size);
	}
	
	/**
	 * 推荐产品
	 * @author 尹雷
	 */
	public function recommend()
	{
		//查询产品列表
		$where['f.is_recommend'] = 2;
		$list = $this->productList1($where, false, false);
		
	}
	
	/**
	 * 查询产品列表，内部使用
	 * @param array $where
	 * @author 尹雷
	 */
	private function productList1($where, $page = false, $size = false, $isReturn = false)
	{
		if($where['fc.status'] !== 0 && !$where['fc.status']) $where['f.status'] = 1;
		if($where['f.status'] !== 0 && !$where['f.status']) $where['f.status'] = 1;
		$fund = M('Fund');
		$field = 'f.id,f.fund_name,f.trader_name,f.trader_id,f.expected_rate,fc.cat_id,fc.cat_name,f.open_start_time,f.open_end_time,f.std_time,f.std_unit,f.recommend_note,f.is_recommend,f.total_count';
		$fund->alias('f')->join('left join __FUND_CATEGORIES__ fc on f.id=fc.fund_id')->where($where);
		if($page !== false && $size !== false) $fund->page($page, $size);
		$list = $fund->field($field)->order("sort_order asc")->select();
		
		//查询出错
		if($list === false) {
			$this->errorLog(__FILE__, __LINE__, M('Fund')->getDbError());
			$return  = array('error' => 1, 'info' => '查询失败');
		//查询成功，有数据
		} else if($list) {
			//TODO:查询产品图片
			$list = $this->productType1($list);
			$list = $this->transactionCountInternal($list);
			$return = array('error' => 0, 'info' => array('code' => 0, 'data' =>$list));
			
		//查询成功，无数据
		} else {
			$return = array('error' => 0, 'info' => array('code' => 1, 'data' =>'查无数据'));
		}
		
		//判断是否返回数据
		if($isReturn) {
			return $list;
		}
		
		$this->ajaxReturn($return);
	}
	
	/**
	 * 计算基金交易数量
	 * @param unknown $list
	 */
	private function transactionCountInternal($list)
	{
		$nowFundValue = D("FundNetvalue")->getnewnetvalue();
		foreach($list as &$fund) {
			$where['fund_id'] = $fund['id'];
			$where['effective_time'] = array('between',array( $fund['open_start_time'], $fund['open_end_time']));
			$count = M('Invest')->where($where)->count();
			$fund['transaction_count'] = $count ? $count : 0;
			$Invest = M('Invest')->where(array('fund_id'=>$fund['id']))->select();
			$profit = 0;
			$have_cast = 0;
			foreach($Invest as $k=>$v){
				$profit += ($nowFundValue[$fund['id']]-$v['unit_value'])*$v['count'];
				$have_cast += $v['amount'];
			}
			$fund['profit'] = $profit;
			$fund['have_cast'] = $have_cast;
		}
		
		return $list;
	}
	/**
	 * 处理产品分类信息
	 * @author 尹雷
	 */
	private function productType1($list)
	{
		$tmp = array();
		foreach($list as $key => $val) {
			if(!$tmp[$val['id']]) {
				unset($val['cat_id']);
				unset($val['cat_name']);
				$tmp[$val['id']] = $val;
			}
		}
		
		foreach($tmp as $key => &$val) {
			foreach($list as $k => $v) {
				if($val['id'] === $v['id']) {
					$val['cats'][] = array('cat_id' => $v['cat_id'], 'cat_name' => $v['cat_name']);
				}
			}
		}
		
		return array_values($tmp);
	}
	
	/**
	 * 产品详情
	 * @author 尹雷
	 */
	public function productDetail()
	{
		$param = I('params');
		
		//根据id获取产品详情
		if(!I('data.id', '', '/^\d+$/', $param)) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		$id = $param['id'];
		
		/* 查询基金产品 */
		$field = 'id,fund_name,fund_code,expected_rate,open_start_time,trade_time,std_time,std_unit,trader_id,min_count,max_count,min_amount,max_amount,total_count,contract_id,contract_name,fund_brief,avatar_title,avatar_content';
		$fundModel =M('Fund');
		$fund = $this->returnOne($fundModel, array('id' => $id), '', $field);
		
		//查询失败
		if($product === false) {
			$this->errorLog(__FILE__, __LINE__, $fundModel->getDbError() . '---' . $fundModel->getError());
			$this->ajaxReturn(array('error' => 1, 'info' => '基金产品查询失败'));
		}
		$fund['std_unit_text'] = C('CLOSE_DATE_UNIT')[$fund['std_unit']];
		$fund['pre_netvalue'] = '';
		$expected_rate = $fund['expected_rate'];

		$fund['month_rate'] = round($expected_rate/12,2);
		$fund['day_rate'] = round($expected_rate/365,2);
		$fund['week_rate'] = round($expected_rate/52,2);

		/* 查询产品类型 */
		$catModel = M('FundCategories');
		$cat = $this->returnList($catModel, array('fund_id' => $id), '', 'cat_id,cat_name');
		if(!$cat) $this->ajaxReturn(array('error' => 1, 'info' => '基金产品类型查询失败'));
		$fund['cat'] = $cat;
		
		/* 查询基金经理 */
		$trader = $this->returnOne('Trader', array('id' => $fund['trader_id']), '', 'id,name,amount,count,birthday,abstract,abstract1,abstract2,avatar_id');
		if(!$trader) $this->ajaxReturn(array('error' => 1, 'info' => '基金经理查询失败'));
		$avatar = $this->returnOne('File', array('id' => $trader['avatar_id']), '', 'id,url');
		if($avatar) $trader['avatar_url'] = $avatar['url'];
		$trader['abstract0'] = $trader['abstract'] ? $trader['abstract'] : '';
		unset($trader['abstract']);
		$fund['trader'] = $trader;
		unset($fund['trader_id']);
		
		/* 查询近5天的基金净值 */
		$where['fund_id'] = $id;
		$netvalue = D('FundNetvalue')->searchNetvalue(1,$where);
		if(!$netvalue) {
			$netvalue = array();
		} else {
			$fund['pre_netvalue'] = array('id' => $netvalue[0]['id'],'value'=>$netvalue[0]['value']);
		}
		$fund['netvalue'] = $netvalue;
		
		/* 查询关注人数 */
		$count = M('UserFund')->where(array('fund_id' => $id, 'status' => 1))->count();
//		//查詢已經最大的購買金額
		//投资明细
		$invest = D('Invest')->searchInvest(array('fund_id'=>$id,'status'=>1), array('page'=>1,'size'=>'5'), 'create_time desc', 'id,user_id,mobile,fund_id,amount,create_time');
		if(!$invest) {
			$invest = array();
		} else {
			D('User')->userAvatar($invest);
		}
		$fund['invest'] = $invest;
		
		//查询投资人提问
		$where = array('fund_id'=>$id, 'status'=>array('gt', 0));
		$question = D('InvestorQuestion')->searchQuestion($where);
		if(!$question) {
			$question = array();
		} else {
			D('User')->userAvatar($question);
		}
		$fund['question'] = $question; 
		
		//查询用户评论
		$where['parent'] = -1;
		$where['fund_id'] = $id;
		$commentList = D('Comment')->commentList($where);
		if($commentList) {
			$commentList = D('User')->userAvatar($commentList);
		} else {
			$commentList = [];
		}
		$fund['comment'] = $commentList;

		//返回结果
		$this->ajaxReturn(array('error' => 0, 'info' => $fund));
	}
	
	/**
	 * 产品分类列表
	 */
	public function productTypeList()
	{
		$cat = M('Categories');
		$list = $this->returnList($cat, array(), '', 'id,name,parent_id');
		//查询出错
		if($list === false) {
			$this->errorLog(__FILE__, __LINE__, $cat->getDbError() . '---' . $cat->getError());
			$this->ajaxReturn(array('error' => 1, 'info' => '查询失败'));
		}
		
		//查询成功
		$parent = array();
		$children = array();
		$return = array('error' => 0, 'info' => '');
		if($list) {
			foreach($list as $key => $val) {
				if($val['parent_id'] == -1) {
					$parent[$val['id']] = $val;
					continue;
				}
				$children[$val['id']] = $val;
			}
			foreach($children as $key => $val) {
				//$parent[$val['parent_id']]['children'][$val['id']] =$val;
				$parent[$val['parent_id']]['children'][] =$val;
			}

			$parent = array_values($parent);
			$return['info'] = array('code' => 0, 'data' => $parent);
		} else {
			$return['info'] = array('code' => 1, 'data' => '查无数据');
		}
		$this->ajaxReturn($return);
	}

	/**
	 * 查询净值信息
	 * @author 尹雷
	 */
	public function netvalueList()
	{
		$param = I('params');
		$fundId = I('data.fund_id', '', '/^\d+$/', $param);
		if(!$fundId) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
	
		//1-查询近7天净值信息，2-近一个月净值信息，3-近三个月，
		//4-近半年，5-近一年，6-从成立至今
		//默认值为1
		$type = I('data.type', '', '/^\d$/', $param);
		if(!$type) $type = 1;
		//构造查询条件
		switch(intval($type) )
		{
			case 1:
				$limit = 5;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-5 day")));
				break;
			case 2:
				$limit = 20;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-30 day")));
				break;
			case 3:
				$limit = 90;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-90 day")));
				break;
			case 4:
				$limit = 180;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-180 day")));
				break;
			case 5:
				$limit = 365;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-365 day")));
				break;
			case 6:
				$limit = false;
				break;
			default:
				$limit = 5;
				$where['netvalue_date'] = array("egt",date("Y-m-d",strtotime("-5 day")));
		}

		$where['fund_id'] = $fundId;
		$option = array();
		//if($limit) $option['limit'] = $limit;
		$list = M("FundNetvalue")->where($where)->order("netvalue_time asc")->select();
		//取第一个值 看是否存在值 如果存在 取出来作为基准值
		if($list[0]['value'] != 0){
			$reference_hs = $list[0]['netvalue_hs'];
			$reference_value = $list[0]['value'];
			$new_list = array();
			foreach($list as $key=>$val){
				$new_list[$key] = $val;
				$netvalue_hsexcess = $val['netvalue_hs']/$reference_hs-1;
				$new_list[$key]['netvalue_hsexcess'] = $netvalue_hsexcess;
				$new_list[$key]['netvalue_cut'] = $val['value']/$reference_value-1-$netvalue_hsexcess;
			}
		}else{
			$new_list = $list;
		}
		//$list = $this->returnList('FundNetvalue', $where, 'netvalue_time', 'id,fund_id,value,netvalue_date,netvalue_time,netvalue_curve,netvalue_cut,netvalue_hs,netvalue_hsexcess', $option);
		$this->ajaxReturn($this->result($new_list));
	}

}